package com.trace.trackshow;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.leador.core.Trace;
import com.leador.listener.OnEntityListener;
import com.leador.listener.OnGeoFenceListener;
import com.leador.listener.OnStartTraceListener;
import com.leador.listener.OnStopTraceListener;
import com.leador.listener.OnTrackListener;
import com.leador.manger.LBSTraceClient;
import com.leador.module.TraceLocation;
import com.leador.module.request.Entity;
import com.leador.module.request.Fence;
import com.leador.module.request.Historyalarm;
import com.leador.module.request.Track;
import com.leador.module.request.TrackRequest;
import com.leador.module.response.Result;
import com.leador.module.response.entity.EntityCloumnResult;
import com.leador.module.response.entity.EntityResult;
import com.leador.module.response.fence.AlarmResult;
import com.leador.module.response.fence.HisAlarmResult;
import com.leador.module.response.fence.FenceCreateResult;
import com.leador.module.response.fence.FenceResult;
import com.leador.module.response.track.TrackCloumnResult;
import com.leador.module.response.track.TrackResult;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lhy on 2016/8/29.
 */
public class TestActivity extends Activity {
    private Context mcontext = null;
    private ListView listView = null;
    private String[] str = {"addEntitycolumn","listEntitycolumn","deletecolumn",
            "addEntity","update","listEntity","deleteEntity","addcTrackolumn",
            "listTrackcolumn","deleteTrackcolumn","gethistory","createfence",
            "updateFence","deleteFence","getListFence","historyAlarm","monitoredStatus","startService","stopService","queryRealtimeLoc"};
    private int fenceId = 107;
    /**
     * 轨迹服务客户端
     */
    protected static LBSTraceClient client = null;
    private OnGeoFenceListener onGeoFenceListener = new OnGeoFenceListener() {
        @Override
        public void onCreateCircularFenceCallback(FenceCreateResult result) {
            Log.e("onCreateFenceCallback",result.toString());
        }

        @Override
        public void onCreateVertexesFenceCallback(FenceCreateResult result) {
            Log.e("onCreateFenceCallback",result.toString());
        }

        @Override
        public void onUpdateFenceCallback(Result result) {
            Log.e("onUpdateFenceCallback",result.toString());
        }

        @Override
        public void onDeleteFenceCallback(Result result) {
            Log.e("onDeleteFenceCallback",result.toString());
        }

        @Override
        public void onQueryFenceListCallback(FenceResult fenceResult) {
            Log.e("onQueryFenceLiallback",fenceResult.toString());
        }

        @Override
        public void onQueryMonitoredStatusCallback(AlarmResult result) {
            Log.e("onQueryFenceLiallback",result.toString());
        }

        @Override
        public void onQueryHistoryAlarmCallback(HisAlarmResult alarmsResult) {
            super.onQueryHistoryAlarmCallback(alarmsResult);
        }

        @Override
        public void onRequestFailedCallback(Result result) {
            Log.e("onRequesCallback",result.toString());
        }
    };

    private OnEntityListener onEntityListener = new OnEntityListener() {

        @Override
        public void onAddEntityCallback(Result result) {
            Log.e("onAddEntityCallback",result.toString());
        }

        @Override
        public void onUpdateEntityCallback(Result result) {
            Log.e("onUpdateEntityCallback",result.toString());
        }

        @Override
        public void onDeleteCallback(Result result) {
            Log.e("onDeleteCallback",result.toString());
        }

        @Override
        public void onListEntityCallback(EntityResult entityResult) {
            Log.e("onListEntityCallback",entityResult.toString());
        }

        @Override
        public void onAddEntityColumn(Result result) {
            Log.e("onAddEntityColumn",result.toString());
        }

        @Override
        public void onQueryEntityColumn(EntityCloumnResult result) {
            Log.e("onQueryEntityColumn",result.toString());
        }

        @Override
        public void onDeleteEntityColumn(Result result) {
            Log.e("onDeleteEntityColumn",result.toString());
        }

        @Override
        public void onRequestFailedCallback(Result result) {
            Log.e("onReque、dCallback",result.toString());
        }

        @Override
        public void onReceiveLocation(TraceLocation location) {
            Log.e("onReceiveLocation",location.toString());
        }
    };

    private OnTrackListener onTrackListener = new OnTrackListener() {
        @Override
        public void onQueryHistoryTrackCallback(TrackResult result) {
            super.onQueryHistoryTrackCallback(result);
            Log.e("onQuCallballback",result.toString());
        }

        @Override
        public void onAddTrackColumn(Result result) {
            Log.e("onAddTrackColumn",result.toString());
        }

        @Override
        public void onQueryTrackColumn(TrackCloumnResult result) {
            Log.e("onQueryTrackColumn",result.toString());
        }

        @Override
        public void onDeleteTrackColumn(Result result) {
            Log.e("onDeleteTrackColumn",result.toString());
        }

        @Override
        public void onRequestSucessCallback(String result) {
            Log.e("onRequestSucessCallback",result.toString());
        }

        @Override
        public Map onTrackAttrCallback() {
            Map<String,String> stringHashMap= new HashMap<String, String>();
            stringHashMap.put("hello","test");
            stringHashMap.put("hello1","test1");
            stringHashMap.put("hello2","test2");
            stringHashMap.put("hello3","test3");
            return stringHashMap;
        }

        @Override
        public void onRequestFailedCallback(Result result) {
            Log.e("onRequestFailedCallback",result.toString());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(new MyBase(str));
        mcontext = this;
        // 初始化轨迹服务客户端
        client = new LBSTraceClient(mcontext);
        client.setProtocolType(0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        appServiceId();
                        break;
                    case 1:
                        listcolumn();
                        break;
                    case 2:
                        deletecolumn();
                        break;
                    case 3:
                        addEntity();
                        break;
                    case 4:
                        updateEntity();
                        break;
                    case 5:
                        listEntity();
                        break;
                    case 6:
                        deleteEntity();
                        break;
                    case 7:
                        addcTrackolumn();
                        break;
                    case 8:
                        listTrackcolumn();
                        break;
                    case 9:
                        deleteTrackcolumn();
                        break;
                    case 10:
                        gethistory();
                        break;
                    case 11:
                        createfence();
                        break;
                    case 12:
                        updateFence();
                        break;
                    case 13:
                        deleteFence();
                        break;
                    case 14:
                        getListFence();
                        break;
                    case 15:
                        historyAlarm();
                        break;
                    case 16:
                        monitoredStatus();
                        break;
                    case 17:
                        startService();
                        break;
                    case 18:
                        stopService();
                        break;
                    case 19:
                        queryRealtimeLoc();
                        break;
                }
            }
        });
    }
    public void queryRealtimeLoc(){
        client.queryRealtimeLoc(this,onEntityListener);
    }

    public void appServiceId(){
//    String ak ="df4c48a96f27d81aa54c3430ed04ec6d";
//    SerEntity entity = new SerEntity();
//    entity.setAk(ak);
//    entity.setDesc("liuhaiyong1@163.com");
//    client.addServiceId(this, entity, new OnServiceListener() {
//        @Override
//        public void onRequestSucessCallback(ServiceResult result) {
//            Log.e("onRequestFailedCallback",result.toString());
//        }
//
//        @Override
//        public void onRequestFailedCallback(Result result) {
//            Log.e("onRequestFailedCallback",result.toString());
//        }
//    });
}

    /**
     * 鹰眼服务ID，开发者创建的鹰眼服务对应的服务ID
     */
    protected static long serviceId = 141352; // serviceId为开发者创建的鹰眼服务ID
    String columKey = "age";
    public void addEntitycolumn(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setColumnKey(columKey);
        entity.setColumnDesc("阵地");
        entity.setIsSearch("1");
        client.addEntitycolumn(entity,onEntityListener);
    }

    public void listcolumn(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        client.listEntitycolumn(entity,onEntityListener);
    }

    public void deletecolumn(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setColumnKey(columKey);
        client.deleteEntitycolumn(entity,onEntityListener);
    }

    private String entityName = "liuhaiyonglhys1@163.com";
    public void addEntity(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setEntityName(entityName);
        entity.setColumnKey("age=123");
        client.addEntity(entity,onEntityListener);
    }

    public void updateEntity(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setEntityName("test");
        entityName = "test";
        entity.setColumnKey("age=321");
        client.updateEntity(entity,onEntityListener);
    }

    public void listEntity(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setEntityName(entityName);
//        entity.setColumnKey("age=123");
        client.listEntity(entity,onEntityListener);
    }

    public void deleteEntity(){
        Entity entity = new Entity();
        entity.setServiceId(serviceId);
        entity.setEntityName(entityName);
        client.deleteEntity(entity,onEntityListener);
    }

    private String teStr = "OKOKOKOKO";
    public void addcTrackolumn(){
        Track track = new Track();
        track.setServiceId(serviceId);
        track.setColumnKey(teStr);
        track.setColumnDesc("测试哈哈哈");
        track.setColumTyppe(3);
        client.addTrackcolumn(track,onTrackListener);
    }

    public void listTrackcolumn(){
        Track track = new Track();
        track.setServiceId(serviceId);
        client.listTrackcolumn(track,onTrackListener);
    }

    public void deleteTrackcolumn(){
        Track track = new Track();
        track.setServiceId(serviceId);
        track.setColumnKey(teStr);
        client.deleteTrackcolum(track,onTrackListener);
    }

    public void gethistory(){
        TrackRequest request = new TrackRequest();
        request.setService_id(serviceId);
        request.setEntity_name("liuhaiyonglhys@163.com");
        request.setStart_time("1472918400");
        request.setEnd_time("1473004799");
        request.setIs_processed(1);
        client.queryHistory(request,onTrackListener);
    }

    public void createfence(){
        Fence fence = new Fence();
        fence.setServiceId(serviceId);
        fence.setFenceName(entityName+"_fence");
        fence.setFenceDesc("test");
        fence.setCreator(entityName);
        fence.setMonitoredPersons(entityName);
        fence.setValidTimes("0800,2300");
        fence.setValidCycle(4);
        fence.setValidDate("");
        fence.setValidDays("");
        fence.setShape(1);
        fence.setCoordType(3);
        fence.setCenter(116.323011 + "," + 39.975646);
        fence.setRadius(100);
        fence.setCoordStr("");
        fence.setAlarmCondition(3);
        client.createFence(fence,
                onGeoFenceListener);
    }

    /**
     * 更新围栏
     */
    private void updateFence(){
        Fence fence = new Fence();
        fence.setServiceId(serviceId);
        fence.setFenceName(entityName+"_fence");
        fence.setFenceDesc("test");
        fence.setCreator(entityName);
        fence.setMonitoredPersons(entityName);
        fence.setValidTimes("0800,2300");
        fence.setValidCycle(4);
        fence.setValidDate("");
        fence.setValidDays("");
        fence.setShape(1);
        fence.setCoordType(3);
        fence.setCenter(116.323011 + "," + 40.975646);
        fence.setRadius(100);
        fence.setCoordStr("");
        fence.setAlarmCondition(3);
        //and create diff
        fence.setObservers("");
        fence.setFenceId(fenceId);
        client.updateFence(fence,
                onGeoFenceListener);
    }

    public void deleteFence(){
        client.deleteFence((int) serviceId,fenceId,onGeoFenceListener);
    }

    public void getListFence(){
        client.getListFence((int) serviceId,String.valueOf(fenceId),"",onGeoFenceListener);
    }
    /**
     * 报警信息
     */
    private void historyAlarm() {
        Historyalarm historyalarm = new Historyalarm();
        historyalarm.setServiceId(serviceId);
        // 围栏ID
        historyalarm.setFenceId(fenceId);
        // 监控对象列表（多个entityName，以英文逗号"," 分割）
        String monitoredPersons = "liuhaiyonglhys@163.com";
        historyalarm.setMonitored_persons(monitoredPersons);
        // 开始时间（unix时间戳）
        int beginTime = (int) (System.currentTimeMillis() / 1000 - 12 * 60 * 60);
        historyalarm.setBeginTime(Long.valueOf(beginTime));
        // 结束时间（unix时间戳）
        int endTime = (int) (System.currentTimeMillis() / 1000);
        historyalarm.setEndTime(endTime);

        historyalarm.setPageNum(1);
        client.queryFenceHistoryAlarmInfo(historyalarm,
                onGeoFenceListener);
    }

    private Trace trace;
    private int traceType = 3;
    public void startService(){
        test();
        // 初始化轨迹服务
        trace = new Trace(getApplicationContext(), serviceId, entityName,
                traceType);
        client.setOnTrackListener(onTrackListener);
        client.startTrace(trace, new OnStartTraceListener() {
            @Override
            public void onTraceCallback(int paramInt, String paramString) {
                Log.e("onTraceCallback",paramInt+","+paramString);
            }
        });
    }

    public void test(){
        Entity en = new Entity();
        en.setServiceId(MainActivity.serviceId);
        en.setColumnKey("testaddEntitycolumn");
        en.setColumnDesc("测试描述");
        en.setIsSearch(String.valueOf(1));
        client.addEntitycolumn(en,onEntityListener);
    }

    public void stopService(){
        client.stopTrace(trace, new OnStopTraceListener() {
            @Override
            public void onStopTraceSuccess() {
                Log.e("stop","sucess");
            }

            @Override
            public void onStopTraceFailed(int paramInt, String paramString) {
                Log.e("onStopTraceFailed",paramInt+","+paramString);
            }
        });
    }
    /**
     * 监控状态
     */
    private void monitoredStatus() {
        // 围栏ID
        // 监控对象列表（多个entityName，以英文逗号"," 分割）
        String monitoredPersons = "liuhaiyonglhys@163.com";
        client.queryMonitoredStatus(MainActivity.serviceId, fenceId, monitoredPersons,
                onGeoFenceListener);
    }


    public class MyBase extends BaseAdapter {
        private String[] str = null;
        private LayoutInflater mInflater;
        public MyBase(String[] str){
            this.str = str;
            mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return str.length;
        }

        @Override
        public Object getItem(int position) {
            return str[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView=mInflater.inflate(R.layout.test_item,null);
            TextView textView = (TextView) convertView.findViewById(R.id.textView);
            textView.setText(str[position]);
            return convertView;
        }
    }
}
